package com.bl.student.service.biz.withdrawals.impl;

import com.bl.student.common.ApiResponseCode;
import com.bl.student.common.CommonServiceException;
import com.bl.student.common.enums.SearchType;
import com.bl.student.common.enums.UserStatus;
import com.bl.student.common.utils.ListUtils;
import com.bl.student.common.utils.UUIDUtils;
import com.bl.student.dao.model.*;
import com.bl.student.dao.repository.UserRepository;
//import com.bl.student.service.biz.config.ConfigService;
//import com.bl.student.service.biz.money.MoneyService;
import com.bl.student.service.biz.user.UserService;
import com.bl.student.service.biz.withdrawals.WithdrawalsService;
//import com.bl.student.service.vo.withdrawals.WithdrawalsAddVo;
import com.bl.student.service.vo.user.UserSimpleInfoVo;
import com.bl.student.service.vo.withdrawals.WithdrawalsListVo;
import com.bl.student.service.vo.withdrawals.WithdrawalsAddVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import com.bl.student.dao.repository.WithdrawalsRepository;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by liangweikang on 18/7/20.
 */
@Service
@Log4j2
public class WithdrawalsServiceImpl implements WithdrawalsService {

    @Autowired
    WithdrawalsRepository withdrawalsRepository;

    @Autowired
    UserService userService;

    @Autowired
    UserRepository userRepository;

//    @Autowired
//    ConfigService configService;

//    @Autowired
//    MoneyService moneyService;

//    @Autowired
//    IncomeRepository incomeRepository;
//
//    @Override
//    public void modify(WithdrawalsModVo withdrawalsModVo) {
//        WithdrawalsEntity withdrawalsEntity = withdrawalsRepository.findOne(withdrawalsModVo.getId());
//
//        if (withdrawalsEntity == null) {
//            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "没有对应信息");
//        }
//
//        UserEntity userEntity = userRepository.findOne(withdrawalsEntity.getMemberid());
//
//        withdrawalsEntity.setEdittime(System.currentTimeMillis() / 1000);
//        withdrawalsEntity.setStatus(withdrawalsModVo.getStatus());
//        withdrawalsRepository.save(withdrawalsEntity);
//
//        if (2 == withdrawalsModVo.getStatus()) {
//            // todo 交易记录表 提现
//            MoneyEntity moneyEntity = new MoneyEntity();
//            moneyEntity.setMemberid(withdrawalsEntity.getMemberid());
//            moneyEntity.setId(UUIDUtils.getUUID());
//            moneyEntity.setDetail("提现："  + " 提现金额：" + withdrawalsEntity.getMoney() + " 提现手续费：" + withdrawalsEntity.getSprice() +  "支付金额：" + withdrawalsEntity.getPmoney());
//            moneyEntity.setMoney(withdrawalsEntity.getMoney());
//            moneyEntity.setTypeid("2");
//            moneyEntity.setClassid(12);// 提现
//            moneyService.addMoney(moneyEntity);
//
//            // 扣除提现人
////            userEntity.setMoney(userEntity.getMoney().subtract(withdrawalsEntity.getMoney()));
////            userEntity.setEdittime(System.currentTimeMillis() / 1000);
////            userRepository.save(userEntity);
//
//            // 公司收入
//            IncomeEntity incomeEntity = new IncomeEntity();
//            incomeEntity.setId(UUIDUtils.getUUID());
//            incomeEntity.setAddtime(System.currentTimeMillis() / 1000);
//            incomeEntity.setEdittime(System.currentTimeMillis() / 1000);
//            incomeEntity.setMemberid(withdrawalsEntity.getMemberid());
//            incomeEntity.setMoney(withdrawalsEntity.getSprice());
//            incomeEntity.setWithdrawlsid(withdrawalsEntity.getId());
//            incomeRepository.save(incomeEntity);
//        }
//    }

    @Override
    public void add(WithdrawalsAddVo withdrawalsAddVo) {
//        UserSimpleInfoVo userSimpleInfoVo = userService.getUserById(userId);


//        BeanUtils.copyProperties(userSimpleInfoVo, userEntity);

//        String encrypt = userEntity.getSafepwd().substring(0,6);
//        String MD5String = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(withdrawalsAddVo.getSafepwd().getBytes()) + encrypt).getBytes());
//        String goodsSafePwd = encrypt + withdrawalsAddVo.getSafepwd() + MD5String;
//
//        if (withdrawalsAddVo.getMoney().compareTo(new BigDecimal(0)) != 1) {
//            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "提现金额不能为负");
//        }
//
//        BigDecimal bigDecimal = withdrawalsAddVo.getMoney().divideAndRemainder(new BigDecimal(100))[1];
//
//        if (bigDecimal.compareTo(new BigDecimal(0)) != 0) {
//            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "提现金额必须为100的整数倍");
//        }
//
//        if (!userEntity.getSafepwd().equals(goodsSafePwd)) {
//            throw new CommonServiceException(ApiResponseCode.SAFE_PASSWORD_ERROR.getCode(), "支付密码错误!");
//        }
//
//        if (UserStatus.LOCKED.equals(userEntity.getStatus())) {
//            throw new CommonServiceException(ApiResponseCode.USER_LOCKED.getCode(), "用户被琐定!");
//        }
//
//        if (userEntity.getMoney().compareTo(withdrawalsAddVo.getMoney()) == -1) {
//            throw new CommonServiceException(ApiResponseCode.NO_ENOUGH_MONEY.getCode(), "账户余额不足");
//        }
        String userMobile = withdrawalsAddVo.getUserMobile();

        List <UserEntity> userEntities =new ArrayList<>();
        if(userMobile != null) {
            userEntities = userRepository.findByMobile(userMobile);
        }

//        List<WithdrawalsEntity> withdrawalsEntityList = withdrawalsRepository.findByPartybIdOrderByCreateTimeDesc(userId);
//        if (withdrawalsEntityList.size() > 0) {
//            WithdrawalsEntity withdrawalsEntity = ListUtils.getFirst(withdrawalsEntityList);
//            long addTime = withdrawalsEntity.getCreateTime();

//            if (isNow(addTime)) {
//                throw new CommonServiceException(ApiResponseCode.NO_ENOUGH_MONEY.getCode(), "今日已提过现啦，明天再提吧！");
//            }
//        }

        if(userEntities!= null && userEntities.size() > 0) {
            UserEntity userEntity = new UserEntity();
            userEntity = userEntities.get(0);
            // 扣除提现人
            userEntity.setMoney(userEntity.getMoney().subtract(withdrawalsAddVo.getMoney()));
            userEntity.setUpdateTime(new Date());
            userRepository.save(userEntity);

            WithdrawalsEntity withdrawalsEntity = new WithdrawalsEntity();
            BeanUtils.copyProperties(withdrawalsAddVo, withdrawalsEntity);
            withdrawalsEntity.setCreateTime(new Date());
            withdrawalsEntity.setUpdateTime(new Date());
            withdrawalsEntity.setPartybId(userEntity.getId());
            withdrawalsEntity.setPartybMobile(userEntity.getMobile());
            withdrawalsEntity.setPartybName(userEntity.getName());
            withdrawalsEntity.setId(UUIDUtils.getUUID());
            withdrawalsEntity.setMoney(withdrawalsAddVo.getMoney());
            withdrawalsRepository.save(withdrawalsEntity);
        }


    }


    @Override
    public WithdrawalsListVo getList(String params, String type, Pageable pageable) {
        WithdrawalsListVo withdrawalsListVo = new WithdrawalsListVo();

        Page<WithdrawalsEntity> withdrawalsEntities;

        switch (type) {
            case "ALL":
                withdrawalsEntities = withdrawalsRepository.findAllByOrderByCreateTimeDesc(pageable);
                break;
            case "MOBILE":
                withdrawalsEntities = withdrawalsRepository.findByPartybMobileOrderByCreateTimeDesc(params, pageable);
                break;
            case "NAME":
                withdrawalsEntities = withdrawalsRepository.findByPartybNameLikeOrderByCreateTimeDesc( "%"+params+ "%" , pageable);
                break;
            case "USERID":
                withdrawalsEntities = withdrawalsRepository.findByPartybIdOrderByCreateTimeDesc(params, pageable);
                break;
            default:
                withdrawalsEntities = withdrawalsRepository.findAllByOrderByCreateTimeDesc(pageable);
        }

        withdrawalsListVo.setTotalCount(withdrawalsEntities.getTotalElements());
        withdrawalsListVo.setList(withdrawalsEntities.getContent());

        return withdrawalsListVo;
    }

    /**
     * 用户提现列表
     * @param userid
     * @param pageable
     * @return
     */
    @Override
    public WithdrawalsListVo getListByUser(String userid, Pageable pageable) {
        WithdrawalsListVo withdrawalsListVo = new WithdrawalsListVo();

        Page<WithdrawalsEntity> withdrawalsEntities;
        withdrawalsEntities = withdrawalsRepository.findByPartybIdOrderByCreateTimeDesc(userid,pageable);
        withdrawalsListVo.setTotalCount(withdrawalsEntities.getTotalElements());
        withdrawalsListVo.setList(withdrawalsEntities.getContent());

        return withdrawalsListVo;
    }

    @Override
    public WithdrawalsListVo getListByTime(String startTime, String endTime) {
        WithdrawalsListVo withdrawalsListVo = new WithdrawalsListVo();
        List <WithdrawalsEntity> withdrawalsEntities;
        withdrawalsEntities = withdrawalsRepository.findByCreateTimeBetweenOrderByCreateTimeDesc(Long.valueOf(startTime).longValue(), Long.valueOf(endTime).longValue());

//        withdrawalsEntities = withdrawalsRepository.findByCreateTimeBetweenOrderByCreateTimeDesc(startTime,endTime);
        withdrawalsListVo.setTotalCount(withdrawalsEntities.size());
        withdrawalsListVo.setList(withdrawalsEntities);

        return withdrawalsListVo;
    }

    private static boolean isNow(long date) {
        //当前时间
        Date before = new Date(date * 1000);
        Date now = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
        //获取今天的日期
        String nowDay = sf.format(now);

        //对比的时间
        String day = sf.format(before);

        return day.equals(nowDay);

    }

}
